import 'dart:async';
import 'dart:developer';
import 'package:audio_session/audio_session.dart';
import 'package:fate_blind_box/ui/cooperation/shop_code/shop_promote_code_page.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:permission_handler/permission_handler.dart';

class MeetAudioPlayer {
  static final MeetAudioPlayer _instance = MeetAudioPlayer._internal();

  factory MeetAudioPlayer() {
    return _instance;
  }

  static MeetAudioPlayer get instance => _instance;

  late AudioSession _session;
  late FlutterSoundPlayer _playerModule;

  MeetAudioPlayer._internal() {
    _initPlayer();
  }

  _initPlayer() async {
    // 设置音频
    _session = await AudioSession.instance;
    await _session.configure(AudioSessionConfiguration(
      avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
      avAudioSessionCategoryOptions:
          AVAudioSessionCategoryOptions.allowBluetooth |
              AVAudioSessionCategoryOptions.defaultToSpeaker,
      avAudioSessionMode: AVAudioSessionMode.spokenAudio,
      avAudioSessionRouteSharingPolicy:
          AVAudioSessionRouteSharingPolicy.defaultPolicy,
      avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
      androidAudioAttributes: const AndroidAudioAttributes(
        contentType: AndroidAudioContentType.speech,
        flags: AndroidAudioFlags.none,
        usage: AndroidAudioUsage.voiceCommunication,
      ),
      androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
      androidWillPauseWhenDucked: true,
    ));
    _playerModule = FlutterSoundPlayer();
    await _playerModule.closePlayer();
    await _playerModule.openPlayer();
    await _playerModule
        .setSubscriptionDuration(const Duration(milliseconds: 10));
  }

  /// 开始播放
  Future<void> startPlayer(String path) async {
    var status = await getPermissionStatus();
    if (status) {
      await _playerModule.startPlayer(
          fromURI: path,
          codec: Codec.pcm16WAV,
          whenFinished: () {
            log('==> 结束播放');
            stopPlayer();
          });
    } else {
      EasyLoading.showToast('播放异常,请先打开麦克风');
    }
  }

  /// 结束播放
  Future<void> stopPlayer() async {
    try {
      await _playerModule.stopPlayer();
      if (kDebugMode) {
        print('===> 结束播放');
      }
    } catch (err) {
      if (kDebugMode) {
        print('==> 错误: $err');
      }
    }
  }

  //动态获取权限
  Future<bool> getPermissionStatus() async {
    Permission permission = Permission.microphone;
    //granted 通过，denied 被拒绝，permanentlyDenied 拒绝且不在提示
    PermissionStatus status = await permission.status;
    if (status.isGranted) {
      return true;
    } else if (status.isDenied) {
      requestPermission(permission);
    } else if (status.isPermanentlyDenied) {
      openAppSettings();
    } else if (status.isRestricted) {
      requestPermission(permission);
    } else {}
    return false;
  }

}
